import axios from 'axios'
import { getToken, removeToken } from '@/utils/cookie'
import { useUserStore } from "@/store/moudel/user.js";
import { ElMessage } from 'element-plus'


const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 36000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        //do something before request is sent
        let token = getToken()
        if (token != null) {
            config.headers.Authorization = 'Mem- ' + token
        }

        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        const userStore = useUserStore();
        if (res.code !== 200) {
            if (res.code == 401) {
                //removeToken()
                removeToken()
                sessionStorage.removeItem("user")
                userStore.setUserInfo(null)
                userStore.setLoginFlag(true)
            }
            //如果是校验微信登录是否授权的接口 则不进行错误输出
            // if (response.config.url !== "/oauth/wechat/is_login") {
            //     ElMessage({ message: res.message, type: 'error' })
            // }
            ElMessage({ message: res.msg, type: 'error', duration: 5 * 1000 })
            return Promise.reject(new Error(res.msg))
        } else {
            return res
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export default service